package com.xlh.virtualization.job.delayed;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.xlh.virtualization.domain.ContainerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;

/**
 * 实验跳转理论 通知容器停止
 *
 * @author cheer
 */
@Component
@Slf4j
public class RedirectToTheoryListener implements ApplicationListener<ApplicationReadyEvent> {

    private static DelayQueue<RedirectToTheoryTask> delayQueue = new DelayQueue<>();

    /**
     * 存储任务 userId contextId taskId
     */
    static Map<ContainerContext, String> recordTable = new ConcurrentHashMap<>();

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        new Thread(() -> {
            while (true) {
                try {
                    RedirectToTheoryTask redirectToTheoryTask = delayQueue.take();
                    threadPoolTaskExecutor.execute(redirectToTheoryTask);
                } catch (Exception e) {
                    log.error("通知容器停止异常", e);
                }
            }
        }).start();
    }

    public static void putTask(RedirectToTheoryTask task) {
        if (StringUtils.isBlank(task.getTaskId())) {
            task.setTaskId(UUID.randomUUID().toString());
            recordTable.put(task.getContainerContext(), task.getTaskId());
        }
        delayQueue.put(task);
    }
}
